import React, { useState, useEffect, use } from "react";
import { List, Button, Dialog, Toast } from "antd-mobile";
import { BankcardOutline } from "antd-mobile-icons";
import './index.css';
import addressApi from '@/api/iap/address'
import { useNavigate, useSearchParams } from "react-router-dom";

export default function MyAddress() {
    const navigate = useNavigate();
    const [addresses, setAddresses] = useState([]); // 地址列表状态
    const [loading, setLoading] = useState(false); // 按钮加载状态
    const [searchParams, setSearchParams] = useSearchParams();
    const [activeId, setActiveId] = useState(null)
    const [pageType, setPageType] = useState('list') // list 列表页 select 选择地址页

    const getAddress = async () => {
        const res = await addressApi.address_list()
        setAddresses(res.data || [])
    }

    const selectAddress = (e, address) => {
        if (pageType == 'select') {
            setActiveId(address.id)
            navigate(`/shopCar?addressId=${address.id}&cartIds=${searchParams.get('cartIds')}&activityId=${searchParams.get('activityId')}`);
        }
    }

    // 从购物车页面跳转过来时，初始化页面类型和选中地址
    const initFromCart = () => {
        const pageType = searchParams.get('type') || 'list'
        setPageType(pageType)
        const addressId = searchParams.get('addressId') || null
        if (addressId) {
            setActiveId(addressId)
        }
    }

    useEffect(() => {
        getAddress()
        initFromCart()
    }, [])

    // 回到“我的页面”
    const goBack = () => {
        navigate("/my"); // 对应你“我的页面”的路由
    };

    const goToEditAddress = (address = null) => {
        navigate(`/editAddress?id=${address ? address.id : ''}&returnUrl=${encodeURIComponent(window.location.pathname + window.location.search)}`)
        // navigate('/editAddress?id=' + (address ? address.id : ''))
        // console.log('跳转到添加/编辑地址页面', `/editAddress?id=${address ? address.id : ''}&returnUrl=${encodeURIComponent(window.location.pathname + window.location.search)}`);
    };

    // 删除地址（带确认弹窗）
    const handleDelete = (address) => {

        Dialog.confirm({
            title: "确认删除",
            content: "删除后该地址将无法恢复，是否继续？",
            confirmText: "删除",
            confirmProps: { color: "danger" },
            onConfirm: async () => {
                let res = await addressApi.address_delete({ id: address.id })
                console.log('删除地址结果', res)
                if (res.msg == "") {
                    Toast.show({ content: '地址删除成功', duration: 1000, type: 'success' });
                    getAddress()
                }
            }
        });
    };

    // 设为默认地址
    const setDefaultAddress = async (address) => {
        let data = {
            id: address.id,
            name: address.name,
            mobile: address.mobile,
            areaId: address.areaId,
            detailAddress: address.detailAddress,
            defaultStatus: true
        }
        try {
            setLoading(true)
            let res = await addressApi.address_update(data)
            if (res.msg == "") {
                Toast.show({ content: '已设为默认地址', duration: 1000, type: 'success' });
                getAddress()
            }
        } finally {
            setLoading(false)
        }
    };


    return (
        <div className="address-page">
            <div className="address-header">我的地址</div>
            {/* 2. 地址列表 */}
            {addresses.length > 0 ? (
                <div className="address-list">
                    {addresses.map(address => (
                        <div key={address.id} className="address-card"
                            onClick={(e) => selectAddress(e, address)}
                            style={address.id == activeId ? { borderColor: '#1677ff' } : {}}>
                            {/* 地址头部：收货人+电话+默认标识 */}
                            <div className="address-header-info">
                                <div className="receiver-info">
                                    <span className="receiver-name">{address.name}</span>
                                    <span className="receiver-phone">{address.mobile}</span>
                                </div>
                                {address.defaultStatus && (<span className="default-tag"> <BankcardOutline size={16} /> 默认</span>)}
                            </div>

                            {/* 地址内容：省市区+详细地址 */}
                            <div className="address-content">
                                <p className="address-area">{address.areaName}</p>
                                <p className="address-detail">{address.detailAddress}</p>
                            </div>

                            {/* 地址操作：设为默认+编辑+删除 */}
                            <div className="address-actions">
                                {!address.defaultStatus &&
                                    <Button onClick={(e) => { e.stopPropagation(); setDefaultAddress(address) }} loading={loading} className="address-actions-item" size="small" color='success' fill="outline" >设为默认</Button>}
                                <Button className="address-actions-item" onClick={(e) => { e.stopPropagation(); goToEditAddress(address) }} loading={loading} size="small" color='primary' fill="outline" >编辑</Button>
                                <Button className="address-actions-item" onClick={(e) => { e.stopPropagation(); handleDelete(address) }} loading={loading} size="small" color='danger' fill="outline" >删除</Button>
                            </div>
                        </div>
                    ))}
                </div>
            ) : (
                // 空地址状态
                <div className="empty-address">
                    <div className="empty-icon"> <BankcardOutline size={48} /></div>
                    <p className="empty-text">暂无收货地址</p>
                    <Button className="add-first-btn" onClick={() => goToEditAddress()}> 添加收货地址 </Button>
                </div>
            )}

            {/* 3. 底部添加地址按钮（固定在底部） */}
            <div className="add-address-footer">
                <Button className="add-address-btn" icon={<BankcardOutline />} onClick={() => goToEditAddress()} >  添加新地址 </Button>
            </div>
        </div>
    );
}